package com.sensePlusVR.activity.user;

import org.xutils.x;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.sensePlusVR.activity.listener.AEditTextCallBack;
import com.sensePlusVR.base.BaseActivity;
import com.sensePlusVR.main.R;
import com.sensePlusVR.net.NetRequestManager;
import com.sensePlusVR.receiver.HomeListener;
import com.sensePlusVR.utils.AppManager;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.EditTextUtils;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MyPageJump;
import com.sensePlusVR.utils.MySharedPreferences;
import com.sensePlusVR.utils.MyToast;
import com.sensePlusVR.utils.StringUtils;
import com.sensePlusVR.utils.UserUtil;
import com.sensePlusVR.widget.EditTextDeleteAll;
/**
 * 
 * @author: Loren
 * @create: 2016-7-4下午7:37:58
 * @desc: 登录界面
 *
 */
@SuppressWarnings("unused")
@ContentView(R.layout.activity_login)
public class LoginActivity extends BaseActivity{
	private final static String TAG = LoginActivity.class.getSimpleName();
   // @ViewInject(R.id.title_bar_title_tv)
    //private TextView tvTitle;
    
    @ViewInject(R.id.login_username)
    private EditTextDeleteAll edtTxtUserName;
    
    @ViewInject(R.id.login_password)
    private EditTextDeleteAll edtTxtPassword;
    
    @ViewInject(R.id.login_show_pwd_iv)
    private ImageView tvShowOrHide;
    
    @ViewInject(R.id.login_name_delete_iv)
    private ImageView login_name_delete_iv;
    
    @ViewInject(R.id.login_pwd_delete_iv)
    private ImageView login_pwd_delete_iv;

    static String userName;
    static String password;
    
	private boolean nameFocus = false;
	private boolean pwdFocus = false;
    
    private Boolean showPassword = false;
    // int type = -1; // 0 表示重从新登录过来的切换用户界面 1表示重注册页面过来的页面
    
    private HomeListener homeListener;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void setMyContentView() {
		x.view().inject(this);
	}
	
	
	
	private OnKeyListener onKey = new OnKeyListener() {

		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_ENTER
					&& event.getAction() == KeyEvent.ACTION_UP) {
				startloginByPhoneNum();
			}
			return false;
		}
	};

	@Override
	public void initData() {
		super.initData();
		homeListener = new HomeListener(this);
	        // Bundle bundle = getIntent().getExtras();
	        // if (bundle != null) {
	        // type = bundle.getInt("type");
	        // }
	        // String username = Sphelper.getString(this, Constant.USERNAME);
	        // // String password = Sphelper.getString(this, Constant.PASSWORD);
	        // if (StringUtil.isNotEmpty(username)) {
	        // edtTxtUserName.setText(Sphelper.getString(this, Constant.USERNAME));
	        // }
	        // // 头像设置s
	        // Bitmap headPortrait = FileUtils.loadImage(this,
	        // Constant.HEADPORTRAIT_NAME);
	        // if (!ObjectUtils.isEmpty(headPortrait)) {
	        // roundImageView.setImageBitmap(headPortrait);
	        // }
	        // if (StringUtil.isNotEmpty(password)) {
	        // edtTxtPassword.setText(Sphelper.getString(this, Constant.PASSWORD));
	        // }
	}
	
	@Override
	public void initView() {
		super.initView();
		AppManager.getInstance().addActivity(this);
		edtTxtPassword.setOnKeyListener(onKey);
		String userName = UserUtil.getLoginNameUser(LoginActivity.this);
		edtTxtUserName.setText(userName);
		edtTxtUserName.setSelection(edtTxtUserName.getText().length());
		
		//检测text变化,使得如果text没有值则一键删除不显示
		edtTxtUserName.setOnAEditTextCallBack(editTextCallBack);
		edtTxtPassword.setOnAEditTextCallBack(editTextCallBack);
		

	}
	
	@Event(value = { R.id.title_bar_left_ib, R.id.login_login,
			R.id.login_forgot_pwd, R.id.login_signup, R.id.login_show_pwd_iv,R.id.login_name_delete_iv,R.id.login_pwd_delete_iv })
	private void setViewOnClick(View view) {
		String msg = this.getString(R.string.msg_common_i_wait);
		int id = view.getId();
		switch (id) {
		// 返回按钮
		case R.id.title_bar_left_ib: {
			AppManager.getInstance().finishAllActivity();
			break;
		}
		case R.id.login_login: // 登陆按钮
			startloginByPhoneNum();
			break;
		case R.id.login_forgot_pwd: // 忘记了密码
			MyPageJump.pageJump(LoginActivity.this, ForgotPwdActivity.class);
			break;

		case R.id.login_signup:
			MyPageJump.pageJump(LoginActivity.this, RegisterActivity.class);
			break;

		case R.id.login_show_pwd_iv:
			if (showPassword) {
				if (checkInputData(edtTxtPassword)) {
					showPassword = !showPassword;
					tvShowOrHide.setImageResource(R.drawable.show_icon);
					edtTxtPassword
							.setTransformationMethod(PasswordTransformationMethod
									.getInstance());
					edtTxtPassword.setSelection(edtTxtPassword.getText()
							.toString().length());
				}
			} else {
				if (checkInputData(edtTxtPassword)) {
					showPassword = !showPassword;
					tvShowOrHide.setImageResource(R.drawable.hide_icon);
					edtTxtPassword
							.setTransformationMethod(HideReturnsTransformationMethod
									.getInstance());
					edtTxtPassword.setSelection(edtTxtPassword.getText()
							.toString().length());
				}
			}
			break;
		case R.id.login_name_delete_iv:
			edtTxtUserName.setText("");
			break;
		case R.id.login_pwd_delete_iv:
			edtTxtPassword.setText("");
			break;
		}
	}
	
	private AEditTextCallBack editTextCallBack = new AEditTextCallBack() {
		
		@Override
		public void onDeleteVisible(View view,boolean isVisible) {
			
			switch (view.getId()) {
			case R.id.login_username:
				if(isVisible){
					
					login_name_delete_iv.setVisibility(View.VISIBLE);
					
				}else{
					
					login_name_delete_iv.setVisibility(View.INVISIBLE);
					
				}
				break;
			case R.id.login_password:
				
				if(isVisible){
					
					login_pwd_delete_iv.setVisibility(View.VISIBLE);
					
				}else{
					
					login_pwd_delete_iv.setVisibility(View.INVISIBLE);
					
				}
				
				
				break;
			}
		}
	};
	
	private boolean checkInputData(EditText editText){
		  if (StringUtils.isEmpty(EditTextUtils.getText(editText))) {
	            return false;
	        }
		return true;
	}
	
	 /**
     * 登陆处理
     * 
     */
    private void startloginByPhoneNum() {
        // 检查画面入力项目是否合法
        if (checkImputData()) {
            // 入力项目合法
            // 赋值
            setInputData();
            // 登陆并保存返回数据
            //CyclingUtils.startLoginRequestResult(this, userName, password);
            //此处上下文一定要填写this，不能填写getApplicationContext(),因为登录成功后要finish掉当前activity
            String userNameLast = UserUtil.getLoginNameUser(this);
            MyLog.d(TAG, "userName : " + userName + " userNameLast : " + userNameLast);
            if(!userName.equals(userNameLast)){
            	MyLog.d(TAG, "clearnData.");
            	UserUtil.clearnData(this);
            }
            NetRequestManager.startLoginRequestResult(this, userName.trim(), password);
        }
    }
    
    /**
     * 检查画面入力项目是否合法
     * 
     * @return true(数据合法) / false(数据不合法)
     */
    private boolean checkImputData() {

    	//用户账号验证
        if (StringUtils.isEmpty(EditTextUtils.getText(edtTxtUserName))) {
            MyToast.showMessage(getApplicationContext(),
                    R.string.msg_common_e_null_username);
            return false;
        }
        //邮箱格式验证
        if (!StringUtils.isEmail(EditTextUtils.getText(edtTxtUserName))) {
        	MyToast.showMessage(getApplicationContext(),
                    R.string.msg_common_e_phone_number_email);
            return false;
        }
        // 密码
        if (StringUtils.isEmpty(EditTextUtils.getText(edtTxtPassword))) {
            // 密码不能为空
            MyToast.showMessage(getApplicationContext(),
                    R.string.msg_common_e_null_password);
            return false;
        }else {
            // 密码长度判断
            if (EditTextUtils.getText(edtTxtPassword).length() < Constant.NUMBER_6
                    || EditTextUtils.getText(edtTxtPassword).length() > Constant.NUMBER_15) {
                // EditTextUtils.setFocusable(edtTxtPassword);
                Toast.makeText(getApplicationContext(),
                        R.string.pwd_min_length, Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        // 业务check通过
        return true;
    }
    
    /**
     * check通过后,赋值
     * 
     */
    private void setInputData() {

        // 获取画面输入的值
        // 用户名-手机号
        userName = EditTextUtils.getText(edtTxtUserName);
        // 密码
        password = EditTextUtils.getText(edtTxtPassword);
    }
    
    @Override
    protected void onDestroy() {
    	   disMissDialog();
    	super.onDestroy();
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	homeListener.start();
    }
    
    @Override
    protected void onPause() {
    	 disMissDialog();
    	 homeListener.stop();
    	super.onPause();
    }

    @Override
    public void onBackPressed() {
        AppManager.getInstance().finishAllActivity();
    }
}
